package cn.b.training.baby_education_training.api;

import cn.b.training.baby_education_training.entity.EncycloCollection;
import cn.b.training.baby_education_training.service.EncycloCollectionService;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * @program: baby_education_training
 * @description
 * @author: wuying
 * @create: 2022-12-04 21:36
 **/
@RestController
@RequestMapping("/encyclo/collection")
public class EncycloCollectionController {
    @Autowired
    private EncycloCollectionService encycloCollectionService;

    @PostMapping
    public ResponseEntity addEncycloCollection(@Valid EncycloCollection encycloCollection){
        try {
            boolean b = encycloCollectionService.addEncycloCollection(encycloCollection);
            if (b){
                JSONObject result = new JSONObject();
                result.put("success","添加成功");
                return ResponseEntity.ok(result);
            }else {
                JSONObject error = new JSONObject();
                error.put("failed","添加失败");
                return ResponseEntity.status(400).body(error);
            }
        } catch (Exception e) {
            e.printStackTrace();
            JSONObject error = new JSONObject();
            error.put("error",e.getMessage());
            return ResponseEntity.status(400).body(error);
        }
    }

    @GetMapping
    public ResponseEntity getEncycloCollectionByUserId(Long userId) {
        try {
            List<EncycloCollection> collections = this.encycloCollectionService.getEncycloCollectionByUserId(userId);
            return ResponseEntity.ok(collections);
        } catch (Exception e) {
            e.printStackTrace();
            JSONObject error = new JSONObject();
            error.put("error", e.getMessage());
            return ResponseEntity.status(400).body(error);
        }
    }


    @DeleteMapping
    public ResponseEntity DeleteEncycloCollectionById(Long id){
        try {
            boolean b = encycloCollectionService.deleteEncycloCollectionById(id);
            if (b) {
                JSONObject result = new JSONObject();
                result.put("success", "删除成功");
                return ResponseEntity.ok(result);
            }else {
                JSONObject error = new JSONObject();
                error.put("failed","删除失败");
                return ResponseEntity.status(400).body(error);
            }
        }catch (Exception e){
            e.printStackTrace();
            JSONObject error = new JSONObject();
            error.put("error",e.getMessage());
            return ResponseEntity.status(400).body(error);
        }
    }
}
